<?php
namespace Components\User\Sha\Mutually\Buy;

class Logic {
  public function updateStatus($id, $status, $data) {
    $currentTime = time();

    switch($status) {
      case '31':
        $model = $this -> findFirstById($id);
        $model['user_mutually_buy_average'] -> status = 35;
        $model['user_mutually_buy_average'] -> pay_time = $currentTime;

        $model['user_mutually_sell_average'] -> status = 35;
        $model['user_mutually_sell_average'] -> receive_time = $currentTime;

				if(isset($data['imageContent']) && !empty($data['imageContent'])) {
          $saveFileName = date('Y').'/'.date('m').'/'.date('d');
          $path = \Phalcon\Di::getDefault() -> getShared('config') -> UPLOAD_DIR . '/'.$saveFileName;
          $saveImage = \Components\Utils::base64_image_content($data['imageContent'], $path);
          if($saveImage['code'] != 0) {

          } else {
            $saveFileName .= '/'.$saveImage['file_name'];
            $model['user_mutually_buy_average'] -> image = $saveFileName;
          }
        }

        $transaction = (new \Phalcon\Mvc\Model\Transaction\Manager()) -> get();

				try {
					$model['user_mutually_buy_average'] -> setTransaction($transaction);
					if(!$model['user_mutually_buy_average'] -> update()) {
						$msgs = $model['user_mutually_buy_average'] -> getMessages();
						$transaction -> rollback($msgs[0] -> getMessage());
					}

					$model['user_mutually_sell_average'] -> setTransaction($transaction);
					if(!$model['user_mutually_sell_average'] -> update()) {
						$msgs = $model['user_mutually_sell_average'] -> getMessages();
						$transaction -> rollback($msgs[0] -> getMessage());
					}

					$transaction -> commit();
				} catch(\Exception $e) {
					return ['code' => -1, 'msg' => $e -> getMessage()];
				}

				return ['code' => 0, 'msg' => '打款成功'];
      default:
        return ['code'=>-1,'msg'=>'此状态未定义'];
    }
  }

  protected function getPaginate($builder, $limit, $page) {
    return ['code' => 0, 'pager'=>(new \Phalcon\Paginator\Adapter\QueryBuilder([
      'builder' => $builder,
      'limit' => $limit,
      'page' => $page
    ])) -> getPaginate()];
  }

  public function findFirstById($id) {
    $builder = $this -> makeBuilder();
    $builder -> andWhere('user_mutually_buy_average.id = '.$id);

    $builder -> addFrom('Components\\User\\Sha\\Mutually\\Sell\\AverageModel', 'user_mutually_sell_average');
    $builder -> andWhere('user_mutually_buy_average.user_mutually_sell_average_id = user_mutually_sell_average.id');

    $builder -> addFrom('Components\\User\\Sha\\Model', 'sell_user');
    $builder -> andWhere('sell_user.id = user_mutually_sell_average.user_id');

    return array_merge(['code'=>0], $builder -> getQuery() -> getSingleResult() -> toArray());
  }
  
  public function makeBuilder() {
    return (new \Phalcon\Mvc\Model\Query\Builder())
      -> from([
        'user' => 'Components\\User\\Sha\\Model',
        'user_mutually_buy' => __NAMESPACE__ . '\\Model',
        'user_mutually_buy_average' => __NAMESPACE__ . '\\AverageModel',
      ])
      -> where('user.id = user_mutually_buy.user_id')
      -> andWhere('user_mutually_buy.id = user_mutually_buy_average.user_mutually_buy_id');
  }
  
  public function pagerUseParameters($limit, $page, $parameters = []) {
    $builder = $this -> makeBuilder()
      -> orderBy('user_mutually_buy_average.status ASC, user_mutually_buy_average.id ASC');

    if(!empty($parameters)) {
      if(isset($parameters['conditions'])) {
        foreach($parameters['conditions'] as $k => $v) {
          foreach($v as $kk => $vv) {
            $builder -> andWhere($k.'.'.$kk.' = '.$vv);
          }
        }
      }
    }

    return $this -> getPaginate($builder, $limit, $page);
  }
  
  public function pager($limit, $page) {
    $builder = $this -> makeBuilder()
      -> andWhere('user_mutually_buy_average.status = 10')
      -> orderBy('user_mutually_buy_average.average_index ASC, user_mutually_buy_average.id ASC');

    return $this -> getPaginate($builder, $limit, $page);
  }
}
